package com.leetcode.q211;

import java.util.ArrayList;
import java.util.List;

/**
 * <p> description: desc</p>
 *
 * @author tanzc
 * @date 2022/3/30
 **/
public class WordDictionary {
    char letter;
    boolean full;
    List<WordDictionary> nextList;

    public WordDictionary() {
        this.letter = ' ';
        this.full = false;
        this.nextList = new ArrayList<>();
    }

    public void addWord(String word) {
        char first = word.charAt(0);
        WordDictionary next = null;
        for (WordDictionary w : nextList) {
            if (w.letter == first) {
                next = w;
                break;
            }
        }

        if (null == next) {
            next = new WordDictionary();
            next.letter = first;
            nextList.add(next);
        }

        if (word.length() > 1) {
            next.addWord(word.substring(1));
        } else {
            next.full = true;
        }
    }

    public boolean search(String word) {
        if (null == nextList) {
            return false;
        }

        char first = word.charAt(0);
        for (WordDictionary next : nextList) {
            if (first == '.' || first == next.letter) {
                if (word.length() > 1) {
                    if (next.search(word.substring(1))) {
                        return true;
                    }
                } else {
                    if (next.full) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
        return false;
    }
}
